package com.hiultra.archive.device.shelve;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Component
public class ShelveWebSocketHandler extends TextWebSocketHandler implements ApplicationListener<ShelveInfoEvent> {
    Log log = LogFactory.get();
    @Autowired
    ShelvesManager shelvesManager;

    private List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
    }


    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("收到消息："+message);
        try {
            // 处理接收到的文本消息
            JSONObject request = JSONUtil.parseObj(message.getPayload());
            String code = request.getStr("code");
            String ip = request.getStr("ip");
            String warehouseCode = request.getStr("warehouseCode");
            String areaCode = request.getStr("areaCode");
            String area = request.getStr("area");
            String faceNo = request.getStr("faceNo");
            if (code.equals("open")) {
                int columnNo = request.getInt("columnNo");
                shelvesManager.open(ip, warehouseCode, areaCode, area, faceNo,columnNo, null);
            } else if (code.equals("close")) {
                shelvesManager.close(ip, warehouseCode, areaCode, area, null);
            } else if (code.equals("stop")) {
                shelvesManager.stop(ip, warehouseCode, areaCode, area, null);
            } else if (code.equals("unlock")) {
                shelvesManager.unlock(ip, warehouseCode, areaCode, area, null);
            }
        }catch (Exception exception){
            log.error("密集架错误："+exception.getMessage());
        }
    }

    public void sendMessageToAllClients(String message) {
        for (WebSocketSession session : sessions) {
            try {
                session.sendMessage(new TextMessage(message));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onApplicationEvent(ShelveInfoEvent event) {
        sendMessageToAllClients(JSONUtil.toJsonStr(event));
    }
}
